import React from 'react';
import {Modal, Form, Input, Select, Radio, Upload, Icon, message} from 'antd';
import {connect} from 'dva';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 8},
};

class EditAdminModalUI extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: this.props.editRow===undefined||this.props.editRow.photo===undefined?[]:
        [
          {
            url: this.props.editRow.photo,
            status: 'done',
            uid: this.props.editRow.id,
          }
        ],
  };
  uploadCancel = () => this.setState({previewVisible: false});

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url,
      previewVisible: true,
    });
  };

  handleChange = (info) => {
    let fileList = info.fileList;
    fileList = fileList.map((file) => {
      if (file.response) {
        if (file.response.status === 200) {
          file.url = file.response.data;
          file.thumbUrl = file.response.data;
          file.status = 'done';
          message.info("文件上传成功");
        } else {
          file.status = 'error';
          message.error("文件上传失败");
          return null;
        }
      }
      return file;
    });
    const newfilelist = new Array();
    for (const f of fileList) {
      if (f != null) {
        newfilelist.push(f);
      }
    }
    const newstate = this.state;
    newstate.fileList = newfilelist;
    this.setState(newstate);
  };

  handleOk = () => {
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (errors) {

      } else {
        if (this.state.fileList.length != 0) {
          values.photo = this.state.fileList[0].url
        }
        this.props.dispatch({
          type: 'admin/update',
          payload: values
        });
        this.props.form.resetFields();
        this.props.showOrHiddenModalVisible(false);
      }
    });
  };
  handleCancel = () => {
    this.props.form.resetFields();
    this.props.showOrHiddenModalVisible(false);
  };

  render() {
    const {previewVisible, previewImage, fileList} = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const allRoles = this.props.editRow.allRoles.map(role => <Select.Option key={role.id}>{role.name}</Select.Option>);
    const roles = this.props.editRow.roles.map(role => role.id + '');
    return (
      <Modal title="编辑用户" visible={true} onOk={() => {
        this.handleOk()
      }} width={620}
             onCancel={() => {
               this.handleCancel()
             }} okText="确认" cancelText="取消" maskClosable={false}
      >
        <Form>
          {
            this.props.form.getFieldDecorator('id', {
              initialValue: this.props.editRow.id,
              rules: [
                {
                  required: true,
                },
              ],
            })(<Input type="hidden"/>)
          }
          <FormItem {...formItemLayout} label="账号" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('userName', {
                initialValue: this.props.editRow.userName,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Input placeholder="账号" size="large" disabled={true}/>)
            }
          </FormItem>
          <FormItem {...formItemLayout} label="手机号" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('cellphone', {
                initialValue: this.props.editRow.cellphone,
                rules: [
                  {
                    type: "string",
                    pattern: "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$",
                    required: true,
                  },
                ],
              })(<Input placeholder="手机号" size="large" disabled={true}/>)
            }
          </FormItem>
          <FormItem {...formItemLayout} label="姓名" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('name', {
                initialValue: this.props.editRow.name,
                rules: [],
              })(<Input placeholder="姓名" size="large"/>)
            }
          </FormItem>
          <FormItem {...formItemLayout} label="性别" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('gender', {
                initialValue: this.props.editRow.gender,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(
                < Radio.Group>
                  <Radio value="Male">男</Radio>
                  <Radio value="Female">女</Radio>
                </ Radio.Group>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label="角色" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('adminRoleIds', {
                initialValue: roles,
              })(
                <Select style={{width: 250}} mode='multiple'>
                  {allRoles}
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label="昵称" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('nickName', {
                initialValue: this.props.editRow.nickName,
                rules: [],
              })(<Input placeholder="昵称" size="large"/>)
            }
          </FormItem>
          <FormItem {...formItemLayout} label="邮箱" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('email', {
                initialValue: this.props.editRow.email,
                rules: [
                  {
                    type: "email",
                  },
                ],
              })(<Input placeholder="邮箱" size="large"/>)
            }
          </FormItem>
          <FormItem {...formItemLayout} label="简介" labelCol={{span: 4}} wrapperCol={{span: 16}}>
            {
              this.props.form.getFieldDecorator('introduce', {
                initialValue: this.props.editRow.introduce,
              })(
                <Input.TextArea size="large" rows={4}/>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label="头像" labelCol={{span: 4}} wrapperCol={{span: 20}}>
            <Upload
              action={"/api/system/file/upload?accessToken=" + JSON.parse(window.sessionStorage.getItem("accessToken"))}
              listType="picture-card"
              fileList={fileList}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {fileList.length >= 1 ? null : uploadButton}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={this.uploadCancel}>
              <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
          </FormItem>
        </Form>
      </Modal>

    );
  }
}

export default connect()(Form.create()(EditAdminModalUI));
